from django.shortcuts import render, redirect
from django.views.generic import View
from django.http import JsonResponse
from .models import *
from hashlib import sha1
import re

# Create your views here.
def check_username(request):
    '''账户否存在'''
    username = request.POST.get("username")
    us = User.objects.filter(username=username)
    if us:
        return JsonResponse({'code': 1, 'msg': '账号已存在'})
    else:
        return JsonResponse({'code': 0, 'msg': '账号不存在'})



class Reg(View):
    # 注册
    def get(self, request):
        return render(request, 'login/reg.html')

    def post(self, request):
        '''
        注册：
            1.获取账号名称，密码
            2.判断账号是否存在
            3.账号和密码设置是否符合要求
            4.保存账号信息
            5.跳转首页
        :param request:
        :return:
        '''
        username = request.POST.get("username")
        cpassword = request.POST.get("cpassword")
        password = request.POST.get("password")
        print(username, cpassword, password)
        if not all([username, cpassword, password]):
            return JsonResponse({'code': 0, 'msg': '有必填项未填写'})
        # 判断是否已经存在
        user = User.objects.filter(username=username).first()
        if user:
            return JsonResponse({'code': 0, 'msg': '账号已存在'})
        if username.isdigit():
            return JsonResponse({'code': 0, 'msg': '账号不能为纯数字'})
        if not re.match("[0-9a-zA-Z!@#$%^&*]{4,16}", password):
            return JsonResponse({'code': 0, 'msg': "密码为4-16位数字、字母"})
        if password != cpassword:
            return JsonResponse({'code': 0, 'msg': "两次输入的密码不一致"})
        pwd_obj = sha1()
        pwd_obj.update(password.encode('utf-8'))
        pwd_sha1 = pwd_obj.hexdigest()
        try:
            u = User()
            u.username = username
            u.password = pwd_sha1
            u.save()
        except Exception as e:
            return JsonResponse({'code': 0, 'msg': f"数据保存失败：{e}"})

        # 注册成功
        if 'username' in request.session.keys():
            del request.session['username']  # 将之间登陆的账号下线
        request.session['username'] = username
        request.session.set_expiry(24*60*60)  # 超时时间

        return JsonResponse({'code': 1, 'msg': '注册成功'})


class Login(View):
    # 登录
    def get(self, request):
        # 返回登录页面规模
        return render(request, 'login/login.html')
    def post(self, request):
        # 登录校验
        username = request.POST.get("username")
        pwd = request.POST.get("password")
        if not all([username, pwd]):
            return JsonResponse({'code': 0, 'msg': '参数错误'})
        # 判断账号是否存在
        user = User.objects.filter(username=username).first()
        if not user:
            return JsonResponse({'code': 0, 'msg': '账号不存在'})

        pwd_obj = sha1()
        pwd_obj.update(pwd.encode('utf-8'))
        pwd_sha1 = pwd_obj.hexdigest()
        if pwd_sha1 != user.password:
            return JsonResponse({'code': 0, 'msg': '密码错误'})

        # 登录成功
        if 'username' in request.session.keys():
            del request.session['username']  # 将之间登陆的账号下线
        request.session['username'] = username
        request.session.set_expiry(24*60*60)  # 超时时间

        return JsonResponse({'code': 1, 'msg': '登录成功', 'url': '/'})

def switchuser(request):
    '''切换用户，删除session信息，然后重定向到login'''
    if "username" in request.session.keys():
        del request.session['username']  # 将之前的账号下线
    return redirect('/')
